const Base = require('./base');

module.exports = class extends Base {
  async listAction() {
    const data = await this.mysql('hanyu_role');
    return this.success(data);
  }
  
  async editAction() {
    const model = this.request.body;
    await this.mysql.thenUpdate('hanyu_role', {id: model.id || null}, model);
    return this.success();
  }
  
  async delAction() {
    const id = this.request.body.id;
    await this.mysql('hanyu_role').where({id: id}).del();
    return this.success();
  }
  
  async searchMenuAction() {
    const text = this.request.query.text || '';
    
    const query = this.mysql('hanyu_menu_group').orderBy('sort');
    let data;
    if (text) {
      data = await query.where('name', 'like', `%${text}%`);
    } else {
      data = await query;
    }
    data.forEach(menu => {
      if (saas.isEmpty(menu.parent_id)) {
        menu.children = data.filter(p => p.parent_id === menu.id);
        menu._showChildren = true;
      }
      if (menu.children)
        menu.children.forEach(menu2 => {
          const children = data.filter(p => p.parent_id === menu2.id);
          if (children) {
            menu2.children = children;
            menu2._showChildren = true;
          }
        })
    });
    return this.success(data.filter(p => saas.isEmpty(p.parent_id)));
  }
  
  async bindAction() {
    const id = this.request.body.id;
    const menuIds = this.request.body.menu_ids;
    await this.mysql('hanyu_role').where({id: id}).update({menu_group_ids: menuIds});
    return this.success();
  }
}